<?php

    #-------------------------------------------------------------#
	# This file is part of the Tekuna MVC Microframework for PHP. #
	# (c) 2009 Niels Jäckel <niels.jaeckel@tekuna.org>            #
	# Please visit http://tekuna.org/ for more information.       #
	#                                                             #
	# This software is licensed under the MIT License. Please     #
	# view the LICENSE file for the full text of this license.    #
    #-------------------------------------------------------------#


	Tekuna :: load('org.tekuna.core.mvc.view.AbstractView');
	Tekuna :: load('org.tekuna.core.mvc.view.TemplateNotFoundException');


	/**
	 * Simple template engine, that replaces placeholders of the form {placeholder} in the given
	 * template file. Nested arrays or objects will be accessible by points.
	 *
	 * Examples:
	 *
	 * {value}, {just.an.array}
	 * {$$} <-- this prints out all values and keys
	 */


	class SimpleView extends AbstractView {


		/**
		 * Processes the SimpleView template engine. If the template file does
		 * not exist or is not readable, a TemplateNotFoundException is thrown.
		 *
		 * @return string the output
		 */

	    public function process() {

			// compose template file path
			$sTemplateFile = $this -> getTemplateBaseDir() . $this -> getTemplate();

	    	// check if template existent and readable
	    	if (! file_exists($sTemplateFile) || ! is_readable($sTemplateFile)) {

	    		throw new TemplateNotFoundException("The template file '$sTemplateFile' does not exist or is not readable.");
	    	}

			// load template from file
			$sOutput = file_get_contents($sTemplateFile);

	    	// assign all variables in this scope
	    	foreach ($this -> getReplacementArray($this -> getAllValues()) as $sVariable => $sValue) {

				// replace {variable} with the assigned value
	    		$sOutput = str_replace("{{$sVariable}}", $sValue, $sOutput);
	    	}

	    	// special replacement of all values if needed
	    	if (strpos($sOutput, '{$$}') !== FALSE) {

	    		$sData = '';
	    		foreach ($this -> getReplacementArray($this -> getAllValues()) as $sVariable => $sValue) {

	    			$sData .= "{{$sVariable}} = $sValue<br />\n";
	    		}

	    		$sOutput = str_replace('{$$}', $sData, $sOutput);
	    	}

	    	// return buffered output
	    	return $sOutput;
	    }


	    protected function getReplacementArray($arrData, $sPrefix = '') {

	    	$arrReturn = array();

	    	// iterate full array
	    	foreach ($arrData as $sVariable => $mValue) {

	    		// prepend prefix if set
    			if ($sPrefix != '') {

    				$sVariable = "$sPrefix.$sVariable";
    			}

				// handle arrays or objects recursively
	    		if (is_object($mValue) || is_array($mValue)) {

	    			$arrReturn = array_merge($arrReturn, $this -> getReplacementArray($mValue, $sVariable));
	    		}
	    		else {

	    			// assign scalars directly
	    			$arrReturn[$sVariable] = $mValue;
	    		}
	    	}

	    	return $arrReturn;
	    }
	}

